package com.example.wzsdk.scan;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;


import com.example.wzsdk.callback.PingSuccessCallback;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Admintor on 2018/1/5.
 */

public class Ping {
    private ExecutorService fixedThread = Executors.newFixedThreadPool(100);
    private List<String> IpList;
    private String IpTitle = null;
    PingSuccessCallback pingSuccessCallback;


    public Ping(Context context, PingSuccessCallback pingSuccessCallback) {
        IpList = new ArrayList<>();
        IpTitle = Index_Ip(context);
        this.pingSuccessCallback = pingSuccessCallback;
    }

    /**
     * @User SunLight
     * @Data 2018/1/11 16:25
     * @Method 获取当前网络可用IP
     **/
    public void PingNetWorkList() {
        IpList.clear();
        for (int i = 1; i < 254; i++) {
            final int finalI = i;
            fixedThread.execute(new Runnable() {
                @Override
                public void run() {
                    if (ping(IpTitle + "." + finalI, 1, new StringBuffer())) {
                        IpList.add(IpTitle + "." + finalI);
                    }
                    if (finalI == 253) {
                        pingSuccessCallback.onSuccess(IpList);
                    }
                }
            });
        }

    }

    /**
     * @User SunLight
     * @Data 2018/1/11 16:25
     * @Method ping局域网内可用IP
     **/
    private boolean ping(String host, int pingCount, StringBuffer stringBuffer) {
        String line = null;
        Process process = null;
        BufferedReader successReader = null;
        String command = "ping -c " + pingCount + " " + host;
        boolean isSuccess = false;
        try {
            process = Runtime.getRuntime().exec(command);
            if (process == null) {
                Log.e("TAG", "ping fail:process is null.");
                append(stringBuffer, "ping fail:process is null.");
                return false;
            }
            successReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            while ((line = successReader.readLine()) != null) {
                Log.e("TAG", line);
                append(stringBuffer, line);
            }
            int status = process.waitFor();
            if (status == 0) {
                Log.e("TAG", "exec cmd success:" + command);
                append(stringBuffer, "exec cmd success:" + command);
                isSuccess = true;
            } else {
                Log.e("TAG", "exec cmd fail.");
                append(stringBuffer, "exec cmd fail.");
                isSuccess = false;
            }
            Log.e("TAG", "exec finished.");
            append(stringBuffer, "exec finished.");
        } catch (IOException e) {
        } catch (InterruptedException e) {
        } finally {
            Log.e("TAG", "ping exit.");
            if (process != null) {
                process.destroy();
            }
            if (successReader != null) {
                try {
                    successReader.close();
                } catch (IOException e) {
                }
            }
        }
        return isSuccess;
    }


    /**
     * @User SunLight
     * @Data 2018/1/11 16:26
     * @Method 获取本地ip
     **/
    public static String Index_Ip(Context context) {
        @SuppressLint("WrongConstant") WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();

        return intToIp(ipAddress).substring(0, intToIp(ipAddress).lastIndexOf("."));
    }

    /**
     * @User SunLight
     * @Data 2018/1/11 16:26
     * @Method 格式化ip地址
     **/
    private static String intToIp(int i) {
        return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + ((i >> 24) & 0xFF);
    }

    private void append(StringBuffer stringBuffer, String text) {
        if (stringBuffer != null) {
            stringBuffer.append(text + "\n");
        }
    }
}
